/*
 * StreetAliasFrame.java
 *
 * Copyright 2008 David D. Emory
 * 
 * This file is part of Five Points. See <http://www.fpdev.org> for
 * additional information regarding the project.
 * 
 * Five Points is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * Five Points is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with Five Points.  If not, see <http://www.gnu.org/licenses/>.
 */
package org.fpdev.apps.admin.gui;

import javax.swing.JFrame;

import java.awt.*;
import java.awt.event.*;
import java.util.Iterator;
import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;
import javax.swing.table.*;
import org.fpdev.apps.admin.AdminClient;

/**
 * A GUI control for managing street aliases, which map alternate street names
 * or common abberivations to the actual street name as it appears in the 
 * link database (e.g. "Ptree" for "Peachtree"; "Tenth" for "10th").
 * 
 * @author demory
 */
public class StreetAliasFrame extends JFrame implements ActionListener, ChangeListener {

  private AdminClient cv_;
  private JList streetList_,  aliasList_;
  private DefaultListModel stListModel_,  alListModel_;
  //private ListSelectionModel streetsLSM_;
  private JSlider slider_;
  private JScrollPane stScrollPane_;
  private JLabel keyLabel_;
  private String selKey_;
  private boolean removingAll_;
  private JButton removeBtn_,  addBtn_,  refreshBtn_,  selectBtn_,  saveBtn_,  closeBtn_;

  public StreetAliasFrame(AdminClient cv) {
    super("Manage Street Aliases");
    cv_ = cv;
    removingAll_ = false;

    slider_ = new JSlider(0, 25, 0);
    slider_.setSnapToTicks(true);
    slider_.setPaintLabels(true);
    slider_.setPaintTicks(true);
    java.util.Dictionary labels = new java.util.Hashtable();
    //JLabel label = new JLabel("A");
    //label.setBorder(new LineBorder(Color.black));
    //label.setFont(label.getFont().deriveFont(9));
    for (int i = 0; i < 26; i++) {
      int chVal = 65 + i;
      char ch = (char) chVal;
      JLabel label = new JLabel("" + ch);
      //label.setBorder(new LineBorder(Color.black));
      label.setFont(label.getFont().deriveFont(9));
      labels.put(new Integer(i), label);
    }
    //labels.put(new Integer(25), new JLabel("Z"));
    //slider_.createStandardLabels(2);
    slider_.setMajorTickSpacing(1);
    slider_.setLabelTable(labels);
    slider_.setBorder(new EmptyBorder(2, 0, 5, 0));
    slider_.addChangeListener(this);

    // main street list:
    stListModel_ = new DefaultListModel();
    streetList_ = new JList(stListModel_);
    streetList_.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

    streetList_.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

      public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting()) {
          return;
        } //Ignore extra messages.
        int selRow = ((ListSelectionModel) e.getSource()).getMinSelectionIndex();
        if (!removingAll_) {
          keySelected(selRow);
        }
      }
    });
    stScrollPane_ = new JScrollPane(streetList_);

    // alias list:

    alListModel_ = new DefaultListModel();
    aliasList_ = new JList(alListModel_);
    aliasList_.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);

    aliasList_.getSelectionModel().addListSelectionListener(new ListSelectionListener() {

      public void valueChanged(ListSelectionEvent e) {
        if (e.getValueIsAdjusting()) {
          return;
        } //Ignore extra messages.
        removeBtn_.setEnabled(true);
      }
    });
    JScrollPane alScrollPane = new JScrollPane(aliasList_);

    removeBtn_ = new JButton("Remove");
    removeBtn_.addActionListener(this);
    addBtn_ = new JButton("Add");
    addBtn_.addActionListener(this);

    JPanel aliasBtnRow = new JPanel();
    aliasBtnRow.setLayout(new BoxLayout(aliasBtnRow, BoxLayout.X_AXIS));
    aliasBtnRow.add(removeBtn_);
    aliasBtnRow.add(addBtn_);

    JPanel rightPanel = new JPanel();
    rightPanel.setLayout(new BoxLayout(rightPanel, BoxLayout.Y_AXIS));
    keyLabel_ = new JLabel("(none selected)");
    keyLabel_.setAlignmentX(JPanel.LEFT_ALIGNMENT);
    rightPanel.add(keyLabel_);
    rightPanel.add(Box.createVerticalStrut(5));
    JLabel alKeysLbl = new JLabel("Alias keys:");
    alKeysLbl.setAlignmentX(JPanel.LEFT_ALIGNMENT);
    rightPanel.add(alKeysLbl);
    alScrollPane.setAlignmentX(JPanel.LEFT_ALIGNMENT);
    rightPanel.add(alScrollPane);
    rightPanel.add(Box.createVerticalStrut(5));
    aliasBtnRow.setAlignmentX(JPanel.LEFT_ALIGNMENT);
    rightPanel.add(aliasBtnRow);

    rightPanel.setBorder(new CompoundBorder(new EmptyBorder(0, 3, 3, 3), new CompoundBorder(new TitledBorder("Selected Street Aliases"), new EmptyBorder(0, 3, 3, 3))));

    refreshBtn_ = new JButton("Refresh");
    refreshBtn_.addActionListener(this);
    selectBtn_ = new JButton("Select");
    selectBtn_.addActionListener(this);
    saveBtn_ = new JButton("Save");
    saveBtn_.addActionListener(this);
    closeBtn_ = new JButton("Close");
    closeBtn_.addActionListener(this);

    JPanel mainBtnRow = new JPanel();
    mainBtnRow.setLayout(new BoxLayout(mainBtnRow, BoxLayout.X_AXIS));
    mainBtnRow.add(Box.createHorizontalGlue());
    mainBtnRow.add(refreshBtn_);
    mainBtnRow.add(selectBtn_);
    mainBtnRow.add(saveBtn_);
    mainBtnRow.add(closeBtn_);
    mainBtnRow.add(Box.createHorizontalGlue());

    JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, stScrollPane_, rightPanel);

    JPanel mainPanel = new JPanel();
    mainPanel.setLayout(new BoxLayout(mainPanel, BoxLayout.Y_AXIS));

    splitPane.setAlignmentX(JPanel.CENTER_ALIGNMENT);
    mainPanel.add(slider_);

    mainPanel.add(splitPane);

    mainPanel.add(Box.createVerticalStrut(5));
    mainBtnRow.setAlignmentX(JPanel.CENTER_ALIGNMENT);
    mainPanel.add(mainBtnRow);
    mainPanel.add(Box.createVerticalStrut(6));

    this.getContentPane().add(mainPanel);

    pack();
    setSize(new Dimension(400, 250));
    splitPane.setDividerLocation(200);
    noneSelected();
  }

  public void stateChanged(ChangeEvent e) {
    JSlider source = (JSlider) e.getSource();
    if (!source.getValueIsAdjusting()) {
      int value = (int) source.getValue();
      cv_.msg("slider: " + value);
      int chVal = 97 + value;
      char ch = (char) chVal;
      String str = "" + ch;
      cv_.msg("str: " + str);
      int row;
      for (row = 0; row < stListModel_.getSize(); row++) {
        String key = (String) stListModel_.get(row);
        if (key.startsWith(str)) {
          break;
        }
      }
      cv_.msg("selecting row: " + row);
      //streetList_.setSelectedIndex(row);
      stScrollPane_.getVerticalScrollBar().setValue(row * (stScrollPane_.getVerticalScrollBar().getMaximum() / stListModel_.getSize()));

    }
  }

  public void show() {
    this.setLocation((cv_.getGUI().getWidth() / 2) - getWidth() / 2 + cv_.getGUI().getX(),
            (cv_.getGUI().getHeight() / 2) - getHeight() / 2 + cv_.getGUI().getY());
    super.show();
    updateStreetList();
  }

  public void updateStreetList() {
    System.out.println("usl:a");
    noneSelected();
    System.out.println("usl:b");
    removingAll_ = true;
    stListModel_.removeAllElements();
    removingAll_ = false;
  /*ObjectIterator keys = cv_.getEngine().getAddrListKeys();
  while(keys.hasNext()) {
  stListModel_.addElement(keys.nextObject());
  }*/
  }

  public void actionPerformed(ActionEvent e) {

    if (e.getSource() == saveBtn_) {
      cv_.getEngine().writeStreetAliasFile();
    }

    if (e.getSource() == closeBtn_) {
      this.hide();
    }

    if (e.getSource() == refreshBtn_) {
      updateStreetList();
    }

    if (e.getSource() == selectBtn_) {
      if (selKey_ != null && selKey_.length() > 0) {
        cv_.getGUI().getMapPanel().selectLinksFromKey(selKey_);
      }
    }

    if (e.getSource() == removeBtn_) {
      cv_.getEngine().getLocations().removeStreetAlias((String) aliasList_.getSelectedValue());
      updateAliasList();
    }

    if (e.getSource() == addBtn_) {
      String alias = JOptionPane.showInputDialog("Specify street alias:");
      if (alias != null) {
        if (cv_.getEngine().getLocations().checkStreetAlias(alias)) {
          JOptionPane.showMessageDialog(this, "An alias by the name \"" + alias + "\"already exists");
        } //else if(cv_.getEngine().checkStreetKey(alias)) JOptionPane.showMessageDialog(this, "A street by the name \""+alias+"\"already exists");
        else {
          cv_.getEngine().getLocations().addStreetAlias(alias, selKey_);
        }
        updateAliasList();
      }
    }
  }

  private void keySelected(int row) {
    selKey_ = (String) stListModel_.get(row);
    keyLabel_.setText("key: " + selKey_);
    removeBtn_.setEnabled(false);
    addBtn_.setEnabled(true);
    updateAliasList();
  }

  private void updateAliasList() {
    alListModel_.removeAllElements();
    Iterator<String> aliases = cv_.getEngine().getLocations().getAliasesForStreet(selKey_);
    while (aliases.hasNext()) {
      alListModel_.addElement(aliases.next());
    }
  }

  private void noneSelected() {
    keyLabel_.setText("(no key selected)");
    removeBtn_.setEnabled(false);
    addBtn_.setEnabled(false);
    alListModel_.removeAllElements();
  }
}

























